package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.common.toJsonString
import io.xxx.omni.oss.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import java.util.*

@Component
class DxysClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://mama.dxy.com/japi/platform/201029020"

    fun execute(store: Store, method: String, request: Map<String, Any>): JsonObject {
        val authorization = store.authorization
        val signMap = TreeMap(request)
        val paramsJson = signMap.toJsonString()
        signMap["method"] = method
        signMap["bizcontent"] = paramsJson
        signMap["appkey"] = authorization["appKey"]
        signMap["token"] = authorization["token"]
        val builder = StringBuilder()
            .append(authorization["appSecret"])
            .append(signMap.entries.joinToString("") { it.key + it.value })
            .append(authorization["appSecret"])
        val sign = DigestUtils.md5Hex(builder.toString())
        signMap["sign"] = sign
        return restTemplate.postForEntity(httpUrl, signMap, String::class.java).body!!.toJsonObject()
    }
}